package com.zhangyongyi.carhome.fragment.recommend.newest;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.google.gson.Gson;
import com.zhangyongyi.carhome.R;
import com.zhangyongyi.carhome.activity.WebViewActivity;
import com.zhangyongyi.carhome.adapter.recommend.newes.NewestRecyclerViewAdapter;
import com.zhangyongyi.carhome.adapter.recommend.newes.NewestViewPagerAdapter;
import com.zhangyongyi.carhome.db.DaoHelper;
import com.zhangyongyi.carhome.entity.greendao.FocusimgList;
import com.zhangyongyi.carhome.entity.greendao.NewesListEntity;
import com.zhangyongyi.carhome.entity.recommend.NewestEntity;
import com.zhangyongyi.carhome.entity.recommend.ResultEntity;
import com.zhangyongyi.carhome.tools.CubeTransformer;
import com.zhangyongyi.carhome.tools.DividerItemDecoration;
import com.zhangyongyi.carhome.tools.FixedSpeedScroller;
import com.zhangyongyi.carhome.tools.MyOnClickListener;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.List;

/**
 * Created by dllo on 16/1/8.
 * 最新
 */
public class NewestFragment extends Fragment implements MyOnClickListener {
    private ViewPager viewPager;
    private RecyclerView recyclerView;
    private NewestRecyclerViewAdapter newestRecyclerViewAdapter;
    private RequestQueue queue;
   //数据库
    private DaoHelper helper;



    FixedSpeedScroller mScroller;
    private Handler handler;
    private int currentItem = 0;
    private int maxItem = 6;

    //轮播图
    private Runnable r = new Runnable() {
        @Override
        public void run() {
            currentItem++;
            viewPager.setCurrentItem(currentItem % maxItem);
            handler.postDelayed(r, 3000);
        }
    };

    private NewestViewPagerAdapter newestViewPagerAdapter;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_recommend_newest, null);
        return v;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewPager = (ViewPager) getActivity().findViewById(R.id.vp_newest);
        newestViewPagerAdapter = new NewestViewPagerAdapter(getChildFragmentManager());
        viewPager.setAdapter(newestViewPagerAdapter);

        //***toos
        viewPager.setPageTransformer(true, new CubeTransformer());


        recyclerView = (RecyclerView) getActivity().findViewById(R.id.rv_newest);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 1);
        recyclerView.setLayoutManager(gridLayoutManager);
        newestRecyclerViewAdapter = new NewestRecyclerViewAdapter(getActivity());
        //分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));

        recyclerView.setAdapter(newestRecyclerViewAdapter);

        //*----*
        newestRecyclerViewAdapter.setMyOnClickListener(this);

        //初始化 RecyclerViewHeader
        RecyclerViewHeader header = (RecyclerViewHeader) getActivity().findViewById(R.id.header);
        header.attachTo(recyclerView, true);


        handler = new Handler();

        controlViewPagerSpeed();
        initData();
        //启动轮播图
        handler.postDelayed(r, 1000);
        //*数据库
        helper = DaoHelper.getInstance();


    }

    private void initData() {
        queue = Volley.newRequestQueue(getActivity());
        String url = "http://app.api.autohome.com.cn/autov4.8.5/news/newslist-pm2-c0-nt0-p1-s20-l0.json";
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
//                Log.d("0000", "onResponse() called with: " + "response = [" + response + "]");
                NewestEntity ne = gson.fromJson(response, NewestEntity.class);
                if (ne != null) {
                    ResultEntity re = ne.getResult();
                    if (re != null) {
                        List<NewesListEntity> newesListEntities = re.getNewslist();
                        if (newesListEntities != null && newesListEntities.size() > 0) {
                            newestRecyclerViewAdapter.addData(newesListEntities);
                            //添加到数据库
                            helper.addNewestList(newesListEntities);
                        }
                        List<FocusimgList> focusimgLists = re.getFocusimg();
                        if (focusimgLists != null && focusimgLists.size() > 0) {
                            newestViewPagerAdapter.addData(focusimgLists);
                            //添加到数据库
                            helper.addFocusimgList(focusimgLists);
                        }
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                //在数据库里取
                newestRecyclerViewAdapter.addData(helper.seacherNewestList());
                newestViewPagerAdapter.addData(helper.seacherFocusimgList());
            }
        }) {

            /**防止乱码 */
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                try {
                    String jsonString = new String(response.data, "UTF-8");
                    return Response.success(jsonString,
                            HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }

        };
        queue.add(request); // 将请求加入到请求队列中
    }

    // 速度控制器
    private void controlViewPagerSpeed() {
        try {
            Field mField;

            mField = ViewPager.class.getDeclaredField("mScroller");
            mField.setAccessible(true);

            mScroller = new FixedSpeedScroller(
                    viewPager.getContext(),
                    new AccelerateInterpolator());
            mScroller.setmDuration(300); // 2000ms
            mField.set(viewPager, mScroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (queue != null) {
            queue.cancelAll(this);
        }
    }


    // 实现接口的方法
    //*----*
    @Override
    public void MyOnClickListener(int id) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), WebViewActivity.class);
        intent.putExtra("id", id);
        Log.d("NewestFragment", "id:" + id);
        getActivity().startActivity(intent);

    }


}



